# -*- coding: UTF-8 -*-
from pathlib import Path

import pandas as pd
from PySide6.QtGui import QIcon, QPixmap, QImage, Qt
from PySide6.QtWidgets import QFileDialog, QMessageBox, QScrollArea, QGroupBox, QDialogButtonBox, QLabel
from PySide6.QtWidgets import QDialog, QVBoxLayout, QFormLayout, QComboBox, QLineEdit, QHBoxLayout, QPushButton
import re
from Icon import icons

def is_valid_ip(ip):
    pattern = re.compile(r"^(\d{1,3}\.){3}\d{1,3}$")
    if pattern.match(ip):
        parts = ip.split(".")
        for part in parts:
            if int(part) > 255:
                return False
        return True
    return False


def show_import_result(self, imported_count, vendor_stats, duplicate_ips):
    """显示导入结果的对话框"""
    dialog = QDialog(self)
    dialog.setWindowTitle("导入结果")
    dialog.setMinimumWidth(400)
    dialog.setMinimumHeight(300)
    
    # 创建主布局
    layout = QVBoxLayout(dialog)
    
    # 创建滚动区域
    scroll_area = QScrollArea()
    scroll_area.setWidgetResizable(True)
    scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    
    # 创建内容容器
    content_widget = QWidget()
    content_layout = QVBoxLayout(content_widget)
    
    # 添加导入统计信息
    if imported_count > 0:
        # 添加总计信息
        total_label = QLabel(f"总计导入：{imported_count} 台设备")
        total_label.setStyleSheet("font-weight: bold; font-size: 14px;")
        content_layout.addWidget(total_label)
        
        # 添加厂商统计信息
        vendor_group = QGroupBox("各厂商设备数量")
        vendor_layout = QVBoxLayout()
        for vendor, count in vendor_stats.items():
            vendor_label = QLabel(f"{vendor}：{count} 台")
            vendor_layout.addWidget(vendor_label)
        vendor_group.setLayout(vendor_layout)
        content_layout.addWidget(vendor_group)
    
    # 添加重复IP信息
    if duplicate_ips:
        duplicate_group = QGroupBox("重复IP设备列表")
        duplicate_layout = QVBoxLayout()
        for device in duplicate_ips:
            duplicate_label = QLabel(f"• {device}")
            duplicate_layout.addWidget(duplicate_label)
        duplicate_group.setLayout(duplicate_layout)
        content_layout.addWidget(duplicate_group)
    
    # 如果没有成功导入任何设备
    if imported_count == 0:
        if duplicate_ips:
            msg_label = QLabel("所有设备均为重复IP，导入失败。")
        else:
            msg_label = QLabel("没有新设备被导入")
        msg_label.setStyleSheet("color: red; font-weight: bold;")
        content_layout.addWidget(msg_label)
    
    # 添加弹性空间
    content_layout.addStretch()
    
    # 将内容容器添加到滚动区域
    scroll_area.setWidget(content_widget)
    layout.addWidget(scroll_area)
    
    # 添加确定按钮
    button_box = QDialogButtonBox(QDialogButtonBox.Ok)
    button_box.accepted.connect(dialog.accept)
    layout.addWidget(button_box)
    
    # 设置对话框样式
    dialog.setStyleSheet("""
        QDialog {
            background-color: white;
        }
        QGroupBox {
            border: 1px solid #cccccc;
            border-radius: 5px;
            margin-top: 10px;
            font-weight: bold;
        }
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 10px;
            padding: 0 3px;
        }
        QLabel {
            padding: 5px;
        }
        QPushButton {
            padding: 5px 15px;
            background-color: #1296db;
            color: white;
            border: none;
            border-radius: 3px;
        }
        QPushButton:hover {
            background-color: #108ecf;
        }
    """)
    
    # 显示对话框
    dialog.exec_()

def import_devices(self):
    """导入设备"""
    # 添加权限检查
    if not self.check_is_admin():
        QMessageBox.warning(self, "权限不足", "只有管理员可以导入设备,请点击右上角的个人中心登录")
        return
        
    initial_dir = Path("device_config").resolve()
    file_path, _ = QFileDialog.getOpenFileName(self, "选择Excel文件", str(initial_dir / "devices.xlsx"),
                                               "Excel Files (*.xlsx *.xls)")
    if not file_path:
        return

    try:
        df = pd.read_excel(file_path)
        imported_count = 0
        vendor_stats = {}
        duplicate_ips = []
        new_devices = []  # 存储新导入的设备
        
        for index, row in df.iterrows():
            host = row["主机名"]
            ip = row["IP地址"]
            vendor = row["厂商"] if not pd.isna(row["厂商"]) else "未知厂商"
            
            if not is_valid_ip(ip):
                QMessageBox.warning(self, "警告", f"设备 {host} 的IP地址 {ip} 无效")
                continue
                
            # 检查IP是否已存在
            ip_exists = False
            for device in self.devices:
                if device["ip"] == ip:
                    duplicate_ips.append(f"{host} ({ip})")
                    ip_exists = True
                    break
                    
            if ip_exists:
                continue
                
            device = {
                "vendor": vendor,
                "device_type": row["设备类型"] if not pd.isna(row["设备类型"]) else "",
                "model": row["型号"] if not pd.isna(row["型号"]) else "",
                "host": row["主机名"] if not pd.isna(row["主机名"]) else "",
                "ip": row["IP地址"] if not pd.isna(row["IP地址"]) else "",
                "remote_type": row["平台类型"] if not pd.isna(row["平台类型"]) else "",
                "protocol": row["协议"] if not pd.isna(row["协议"]) else "ssh",
                "port": row["端口"] if not pd.isna(row["端口"]) else "22",
                "username": row["用户名"] if not pd.isna(row["用户名"]) else "",
                "password": row["密码"] if not pd.isna(row["密码"]) else "",
                "enable_password": row["enable密码"] if row["平台类型"].lower() not in ["华为", "华三"] else "",
                "online": "离线",
                "version": "",
                "cpu": "",
                "memory": "",
                "uptime": "",
                "fan": "",
                "power": "",
                "temperature": "",
                "update_time": ""
            }
            
            new_devices.append(device)
            imported_count += 1
            vendor_stats[vendor] = vendor_stats.get(vendor, 0) + 1

        if new_devices:
            # 批量添加新设备
            self.devices.extend(new_devices)
            self.save_devices()
            
            # 重置筛选条件
            self.filtered_indices = []
            
            # 重置到第一页
            self.current_page = 1
            
            # 更新表格显示
            self.update_table()
            
            # 立即开始检测新设备的在线状态
            new_device_indices = list(range(len(self.devices) - len(new_devices), len(self.devices)))
            self.start_ping_thread(new_device_indices)
        
        # 显示导入结果
        self.show_import_result(imported_count, vendor_stats, duplicate_ips)
            
    except Exception as e:
        QMessageBox.warning(self, "警告", f"导入设备信息时发生错误: {str(e)}")


def show_add_device_dialog(self):
    """显示添加设备对话框"""
    # 添加权限检查
    if not self.check_is_admin():
        QMessageBox.warning(self, "权限不足", "只有管理员可以添加设备,请点击右上角的个人中心登录")
        return
        
    dialog = QDialog(self)
    dialog.setWindowTitle("添加设备")
    dialog_layout = QVBoxLayout(dialog)

    form_layout = QFormLayout()
    dialog_layout.addLayout(form_layout)

    self.vendor_combo = QComboBox()
    self.vendor_combo.addItems(["华为", "华三", "思科", "锐捷", "中兴", "Juniper", "迈普", "其他厂商"])
    if "vendor" in self.last_device_info:
        self.vendor_combo.setCurrentText(self.last_device_info["vendor"])
    form_layout.addRow("厂商", self.vendor_combo)

    self.device_type = QComboBox()
    self.device_type.addItems(["交换机", "路由器", "防火墙", "负载均衡", "VPN", "AC控制器", "其他设备"])
    if "device_type" in self.last_device_info:
        self.device_type.setCurrentText(self.last_device_info["device_type"])
    form_layout.addRow("设备类型", self.device_type)
    self.model_input = QLineEdit()
    self.model_input.setPlaceholderText("WS-C3850-24P")
    if "model" in self.last_device_info:
        self.model_input.setText(self.last_device_info["model"])
    form_layout.addRow("型号", self.model_input)

    self.host_input = QLineEdit()
    self.host_input.setPlaceholderText("SW01")
    if "host" in self.last_device_info:
        self.host_input.setText(self.last_device_info["host"])
    form_layout.addRow("主机名", self.host_input)

    self.ip_input = QLineEdit()
    self.ip_input.setPlaceholderText("192.168.1.1")
    if "ip" in self.last_device_info:
        self.ip_input.setText(self.last_device_info["ip"])
    form_layout.addRow("ip地址", self.ip_input)

    self.remote_type = QComboBox()
    self.remote_type.addItems(["huawei", "hp_comware", "cisco_ios", "ruijie_os", "zte_zxros", "juniper_junos", "maipu"])
    if "remote_type" in self.last_device_info:
        self.remote_type.setCurrentText(self.last_device_info["remote_type"])
    form_layout.addRow("远程类型", self.remote_type)

    self.protocol_combo = QComboBox()
    self.protocol_combo.addItems(["ssh", "telnet"])
    if "protocol" in self.last_device_info:
        self.protocol_combo.setCurrentText(self.last_device_info["protocol"])
    form_layout.addRow("远程协议", self.protocol_combo)

    self.port_combo = QComboBox()
    self.port_combo.addItems(["22", "23"])
    self.port_combo.setEditable(True)
    if "port" in self.last_device_info:
        self.port_combo.setCurrentText(str(self.last_device_info["port"]))
    form_layout.addRow("远程端口", self.port_combo)

    self.username_input = QLineEdit()
    self.username_input.setPlaceholderText("admin")
    if "username" in self.last_device_info:
        self.username_input.setText(self.last_device_info["username"])
    form_layout.addRow("用户名", self.username_input)

    self.password_input = QLineEdit()
    self.password_input.setPlaceholderText("Admin@123")
    if "password" in self.last_device_info:
        self.password_input.setText(self.last_device_info["password"])
    form_layout.addRow("密码", self.password_input)

    self.enable_password_input = QLineEdit()
    self.enable_password_input.setPlaceholderText("Admin@123")
    if "enable_password" in self.last_device_info:
        self.enable_password_input.setText(self.last_device_info["enable_password"])
    form_layout.addRow("enable密码", self.enable_password_input)

    buttons_layout = QHBoxLayout()
    dialog_layout.addLayout(buttons_layout)

    add_button = QPushButton("添加")
    add_button.setIcon(
        QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icons.add_icon_base64)))))
    add_button.setStyleSheet(
        "background-color: white; color: black; border-radius: 5px; font-weight: bold; border: 1px solid #1296DB; padding: 3px;")
    add_button.setCursor(Qt.PointingHandCursor)
    add_button.clicked.connect(lambda: self.add_device_from_dialog(dialog))
    buttons_layout.addWidget(add_button)

    cancel_button = QPushButton("取消")
    cancel_button.setIcon(
        QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icons.delivery_cancel)))))
    cancel_button.setStyleSheet(
        "background-color: white; color: black; border-radius: 5px; font-weight: bold; border: 1px solid #1296DB; padding: 3px;")
    cancel_button.setCursor(Qt.PointingHandCursor)
    cancel_button.clicked.connect(dialog.reject)
    buttons_layout.addWidget(cancel_button)

    dialog.exec_()
